﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.Sms.V20210111;
using TencentCloud.Sms.V20210111.Models;
using Microsoft.Extensions.Logging;

namespace MDT.LifeSewagePlatform.Conmmon
{
    public class SendPhoneNumberMsg : ISendPhoneNumberMsg
    {
        private readonly ILogger<SendPhoneNumberMsg> _logger;
        public SendPhoneNumberMsg(ILogger<SendPhoneNumberMsg> logger)
        {
            _logger = logger;
        }
        public async Task<bool> Send(AuthModel auth,ValueModel Value)
        {
          return await Task.Run(()=> { 
             try
            {
                Credential cred = new Credential
                {
                    SecretId = auth.SecretId,//"AKIDhDSREkzxe5B1astd8NL2SbT4ORFm22mF",
                    SecretKey = auth.SecretKey //"FMLAqHSLxIMBj0ziALFrCG3ZnkQpwmLd"
                };
                ClientProfile clientProfile = new ClientProfile();
                clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256;
                HttpProfile httpProfile = new HttpProfile();
                httpProfile.ReqMethod = "POST";
                httpProfile.Timeout = 10;
                httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");
                clientProfile.HttpProfile = httpProfile;//ap-guangzhou
                SmsClient client = new SmsClient(cred, auth.Region, clientProfile);
                SendSmsRequest req = new SendSmsRequest();
                req.SmsSdkAppId = auth.SdkAppId; //"1400564969";
                req.SignName = auth.SignName;// "迈多特云";
                req.ExtendCode = "";
                req.SenderId = "";
                req.SessionContext = "";
                req.PhoneNumberSet = GetToSendNumber(Value.PhoneNumbers);
                req.TemplateId = auth.TempID; //"1093153";
                req.TemplateParamSet = Value.Parametes;
                SendSmsResponse resp = client.SendSmsSync(req);
                _logger.LogInformation(AbstractModel.ToJsonString(resp));

                if (resp!=null&& resp.SendStatusSet.Count()>0 )
                {
                    if (resp.SendStatusSet[0].Code.Contains("OK"))
                    {
                        return true;
                    }
                }
                return false ;
            }
            catch (Exception ex)
            {
                _logger.LogInformation(ex.Message);
                return false;
            }
            });
        }

        private string [] GetToSendNumber(string [] strNumbers)
        {
            for (int i=0;i<strNumbers.Length;i++)
            {
                strNumbers[i] = $"+86{strNumbers[i]}";
            }
            return strNumbers;
        }
    }
}
